package com.yonyou.cyxdms.sysAuth.service.service.manage.company;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yonyou.cms.channel.client.feign.CmsChannelCommonClient;
import com.yonyou.cms.channel.client.vo.message.DealerAttachVO;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.basedata.client.domains.vo.BrandCacheVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.SeriesCacheVO;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonBrandService;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonSeriesService;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.entity.*;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.service.org.OrgService;
import com.yonyou.cyxdms.sysAuth.service.utill.BeanUtils;
import com.yonyou.cyxdms.sysAuth.service.vo.companyorg.DealerchannelVO;
import com.yonyou.cyxdms.sysAuth.service.vo.org.OrgBrandSeriesVO;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataDictConstants;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.DealerInfoDTO;
import com.yonyou.cyxdms.sysmanage.client.vo.org.OrgAndParentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class DealerBasicinfoServiceImpl implements DealerBasicinfoService {

    @Autowired
    DealerchannelMapper dealerchannelMapper;
    @Autowired
    BaseCommonBrandService baseCommonBrandService;
    @Autowired
    BaseCommonSeriesService baseCommonSeriesService;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    CmsChannelCommonClient cmsChannelCommonClient;
    @Autowired
    OrgService orgService;
    @Autowired
    DealerInfoMapper dealerInfoMapper;
    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    private TrOrgMapper trOrgMapper;

    /**
     * 通过code查询经销航基本信息
     *
     * @return
     * @author maxiongjian
     * @since 2019/7/9
     */
    @Override
    public DealerchannelVO getDealerChannelByCode(Long companyId, String appId) {
        DealerchannelVO dealerchannel = dealerchannelMapper.Dealerchannel(companyId, appId);
        String dealerForm = cmsChannelCommonClient.getFinanceCompanyIdByOwnerCode(dealerchannel.getDealerCode());
        String dealerFormName = "";
        if("1".equals(dealerForm)){
            dealerFormName = "电车";
        }else if("2".equals(dealerForm)){
            dealerFormName = "油车";
        }else{//3
            dealerFormName = "油车||电车";
        }

        DealerAttachVO dealerattachvo = cmsChannelCommonClient.getDealerInfoByDealerCode(dealerchannel.getDealerCode()).getData();
        dealerchannel.setDealerFormName(dealerFormName);
        dealerchannel.setProvinceId(dealerattachvo.getProvinceId());
        dealerchannel.setCityId(dealerattachvo.getCityId());
        dealerchannel.setCounty(dealerattachvo.getDistrictId());
        dealerchannel.setCompanyNameEN(dealerattachvo.getDealerShortname());
        Long deptId = dealerattachvo.getDeptId();
        Long officeId =  dealerattachvo.getOfficeId();
        String deptName = "";
        String officeName = "";
        if(!ObjectUtils.isEmpty(deptId)){
            OrgAndParentVO orgServiceOrg = orgService.getOrg(String.valueOf(deptId));
            deptName = orgServiceOrg.getOrgName();
            dealerchannel.setDeptName(deptName);

        }
        if(!ObjectUtils.isEmpty(officeId)){
            OrgAndParentVO organdparentvo = orgService.getOrg(String.valueOf(officeId));
            officeName = organdparentvo.getOrgName();
            dealerchannel.setOfficeName(officeName);
        }

        //根据orgId查询车系品牌信息
        if (null == dealerchannel.getOrgId()) {
            return dealerchannel;
        }
        List<OrgBrandSeriesVO> list1 = orgMapper.getOrgBrandSeries(dealerchannel.getOrgId().toString());
        if (list1.size() > 0) {
            for (OrgBrandSeriesVO orgBrandSeriesVO : list1) {
                if (StringUtils.isEquals(orgBrandSeriesVO.getBillType(),
                        String.valueOf(SysAuthDictCodeConstants.BILL_TYPE_ORG_RELATION_BRAND)) ) {
                    //查询品牌
                    BrandCacheVO brandCacheVO = baseCommonBrandService.getValueByBrandId(orgBrandSeriesVO.getBrandId().toString());
                    if (null != brandCacheVO) {
                        orgBrandSeriesVO.setBrandName(brandCacheVO.getBrandName());
                        orgBrandSeriesVO.setBrandId(brandCacheVO.getBrandId());
                    }
                } else {
                    //查询车系
                    SeriesCacheVO seriesCacheVO = baseCommonSeriesService.getValueBySeriesId(orgBrandSeriesVO.getSeriesId().toString());
                    if (null != seriesCacheVO) {
                        orgBrandSeriesVO.setBrandName(seriesCacheVO.getBrandName());
                        orgBrandSeriesVO.setBrandId(seriesCacheVO.getBrandId());
                        orgBrandSeriesVO.setSeriesName(seriesCacheVO.getSeriesName());
                    }

                }

            }
        }
        dealerchannel.setListOBSVO(list1);
        return dealerchannel;
    }

    /**
     * 查询除了自己的所有dealer信息
     *
     * @param
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author renwd
     * @since 2019/7/9
     */
    @Transactional(readOnly = true)
    @Override
    public List<Map<String, Object>> getDealerExceptSelf() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return dealerchannelMapper.getDealerExceptSelf(loginInfoDto.getOwnerCode());
    }

    /**
     * 获取经销商基本信息
     *
     * @author dengqiang
     * @since 2019/7/25
     */
    @Override
    public Map<String, Object> getDealerBasicinfo() {

        return dealerchannelMapper.getDealerBasicinfo();

    }

    /**
     * 睿蓝新增销售信息
     * @param dealerInfoDTO
     * @return
     */
    @Override
    public Integer insertDealerInfo(DealerInfoDTO dealerInfoDTO){
        DealerInfoPO dealerinfopo = dealerInfoMapper.selectOne(new LambdaQueryWrapper<DealerInfoPO>()
                .eq(DealerInfoPO::getAppId, dealerInfoDTO.getAppId())
                .eq(DealerInfoPO::getCompanyId, dealerInfoDTO.getCompanyId()));
        if(dealerinfopo != null){
            throw new ServiceBizException("所选经销商公司下已经存在销售信息");
        }
        dealerinfopo = new DealerInfoPO();
        BeanUtils.copyProperties(dealerInfoDTO, dealerinfopo);

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long factoryCompanyId = companyMapper.findFactoryIdByAppId(loginInfoDto.getAppId());
        if (factoryCompanyId == null) {
            throw new ServiceBizException("您输入的AppID可能不存在");
        }

        //保存经销商组织信息
        OrgPO orgpo = new OrgPO();
        orgpo.setCompanyId(dealerinfopo.getCompanyId().longValue());
        orgpo.setAppId(loginInfoDto.getAppId());
        orgpo.setOrgName(dealerinfopo.getDealerName());
        orgpo.setOrgShortName(dealerinfopo.getDealerName());
        orgpo.setOrgCode(dealerinfopo.getDealerCode() + "SE");
        orgpo.setOrgShortName(dealerinfopo.getDealerName());
        orgpo.setOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER);
        orgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
        orgpo.setIsValid(10011001);
        orgpo.setRecordVersion(0);
        orgpo.setOrgId(Long.MAX_VALUE);
        orgMapper.insert(orgpo);

        //保存经销商信息
        dealerinfopo.setAppId(loginInfoDto.getAppId());
        dealerinfopo.setOrgId(orgpo.getOrgId().intValue());
        dealerinfopo.setOrgType(ManageDictCodeConstants.ORG_TYPE_ASC);
        dealerinfopo.setValidStatus(BaseDataDictConstants.IS_VALID);
        dealerinfopo.setFactoryCompanyId(factoryCompanyId.intValue());
        dealerInfoMapper.insert(dealerinfopo);

        //保存经销商组织关系信息 父级id为经销商所在公司组织id
        CompanyPO companypo = companyMapper.selectById(dealerinfopo.getCompanyId());
        TrOrgPO trorgpo = new TrOrgPO();
        trorgpo.setOrgId(orgpo.getOrgId());
        trorgpo.setParentOrgId(companypo.getOrgId().longValue());
        trOrgMapper.insert(trorgpo);

        return dealerinfopo.getOrgId();
    }

}
